package com.fuqi.android.zhongcai.application;

import com.fuqi.android.zhongcai.base.Constants;
import com.fuqi.android.zhongcai.sql.DaoMaster;
import com.fuqi.android.zhongcai.sql.DaoSession;
import com.fuqi.android.zhongcai.sql.User;
import com.fuqi.android.zhongcai.sql.UserDao;
import com.fuqi.framework.application.QuickApplication;

import de.greenrobot.dao.query.QueryBuilder;

public class UniApplication extends QuickApplication {

    private String currentRole = Constants.ROLE_SGDZ;
    private User userInfo;
    private UserDao userDao;
    private final int USER_ID_FLAG = 1;
    public static UniApplication getInstance() {
        return (UniApplication) QuickApplication.getInstance();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initDb();
        initData();

    }

    private void initData() {

        getUserInfo();
        if (userInfo != null){

            currentRole = userInfo.getRolecode();
        }

    }


    private void initDb() {

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(getApplicationContext(), Constants.DB_NAME, null);
        DaoMaster daoMaster = new DaoMaster(helper.getReadableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        userDao = daoSession.getUserDao();
    }


    public String getCurrentRole() {
        return currentRole;
    }

    public void setCurrentRole(String currentRole) {
        this.currentRole = currentRole;
    }

    public User getUserInfo() {

        if (userInfo == null) {
            QueryBuilder qb = userDao.queryBuilder();
            userInfo = (User) qb.where(UserDao.Properties.Id.eq(USER_ID_FLAG)).unique();
        }

        return userInfo;
    }

    public void setUserInfo(User userInfo) {

        currentRole = userInfo.getRolecode();
        userInfo.setId(USER_ID_FLAG);
        userDao.insert(userInfo);
        this.userInfo = userInfo;
    }


    public void deleteUserInfo(){

        userDao.deleteAll();

    }


    public void updateUserInfo(){


    }


    public boolean hasLogin(){

        getUserInfo();

        if (userInfo == null){

            return false;

        } else if(userInfo.getUserid().equals("")){

            return false;
        }else {

            return true;

        }

    }


}